package com.witframework.baseapp.security.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.witframework.PropertiesConstants;
import com.witframework.baseapp.security.BaseUser;
import com.witframework.baseapp.security.UserSession;
import com.witframework.core.ApplicationProperties;

/**
 * <P>
 * application filter,set some application param
 * </P>
 * 
 * @author wuxinyang
 * 
 */
public class GuestFilter implements Filter {
	private boolean cond=false;
	private String [] excludeURIs;
	public void doFilter(ServletRequest req, ServletResponse res,FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;	
		String command=request.getParameter("command");
		boolean login=command!=null&&command.equalsIgnoreCase("login");
		if(login)
			request.getSession().invalidate();
		String uri=request.getRequestURI();
		if(cond&&request.getSession().getAttribute("UserSession")==null
				&&!uri.equals("loginController"+ApplicationProperties.getProperty(PropertiesConstants.WIT))
				&&uri.indexOf("top.jsp")<0
				&&uri.indexOf("menu.jsp")<0
				&&!uri.equals("long")){	
			boolean exclude=false;
			for(String excludeUri:excludeURIs){
				if(uri.indexOf(excludeUri)>=0){
					exclude=true;
					break;
				}
			}
			if(!exclude){
				BaseUser user=new BaseUser();
				user.setId("_GUEST_USER_TEMP_00");
				user.setUsername("guest");
				user.setName("访客");
				UserSession us=new UserSession(user);		
				request.getSession().setAttribute("UserSession", us);				
			}
		}
		
		chain.doFilter(request, response);
		
	}
	public void init(FilterConfig filterConfig) throws ServletException {
		cond=Boolean.valueOf(filterConfig.getInitParameter("cond")).booleanValue();
		String excludes=filterConfig.getInitParameter("exclude");
		if(excludes!=null)
			excludeURIs=StringUtils.split(excludes,",");
	}	
	public void destroy() {		
	}
}
